package com.station.model;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.databinding.DataBindingUtil;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;

import com.daimajia.swipe.util.Attributes;
import com.google.gson.Gson;
import com.station.R;
import com.station.adapter.Tab4ItemAdapter;
import com.station.bean.BaseBean;
import com.station.bean.BaseTypeBean;
import com.station.bean.DTBean;
import com.station.bean.DTListBean;
import com.station.bean.Tab2RefreshEvent;
import com.station.bean.XJBean;
import com.station.databinding.ActivityListBinding;
import com.station.databinding.LayoutDtBinding;
import com.station.databinding.LayoutEdtBinding;
import com.station.http.MNetHttp;
import com.station.listener.HttpListener;
import com.station.listener.ItemEditClick;
import com.station.listener.LoadStatusListener;
import com.station.listener.RefreshListener;
import com.station.listener.RxHttpListener;
import com.station.util.BindingUtil;
import com.station.util.GsonUtil;
import com.station.util.PreferencesUtil;
import com.station.util.RefreshUtil;
import com.station.util.Static;
import com.station.widget.RVItemDecoration;
import com.station.widget.nicespinner.NiceSpinner;
import com.station.widget.slidingmenu.SlidingMenu;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by nbzl on 2017/10/17.
 */
public class Tab4Model extends BaseModel {
    private EditText fzrEdit, deviceedit, pddedit;
    //private NiceSpinner spinnerbmtype;
    private ActivityListBinding binding;
    private RefreshUtil refreshUtil;
    private LoadStatusListener statusListener;
    private Tab4ItemAdapter adapter;
    private List<Object> datalist;

    private SlidingMenu slidingMenu;
    private android.support.v7.app.AlertDialog.Builder builder;
    private Map<String, String> params;
    private List<BaseTypeBean> pplist;
    private List<String> spinnerdata;

    private int page = 1, editposition = 0;
    private String brand_id = "", brandname = "", type = "", id = "";

    public String[] typevaluelist = new String[]{"备用", "在用", "注销", "外接"};
    public String[] typekeylist = new String[]{"0", "1", "2", "3"};

    public String[] typevaluelist1 = new String[]{"请选择", "备用", "在用", "注销", "外接"};
    public String[] typekeylist1 = new String[]{"", "0", "1", "2", "3"};

    public String searchtype = "", brand_ids = "";


    public Tab4Model(Context context, LoadStatusListener statusListener) {
        super(context);
        this.statusListener = statusListener;
        pplist = new ArrayList<BaseTypeBean>();
        spinnerdata = new ArrayList<String>();
        pplist.add(new BaseTypeBean("", "请选择"));
        datalist = new ArrayList<Object>();
        params = new HashMap<String, String>();
        binding = DataBindingUtil.inflate(LayoutInflater.from(context), R.layout.activity_list, null, false);
        //initAdapter();
        refreshUtil = new RefreshUtil(context, binding.ptrLayout, new Refresh());
        refreshUtil.initRefreshView();
        initMenu();
    }

    public void initMenu() {
        // 设置滑动菜单的属性值
        slidingMenu = new SlidingMenu(context);
        slidingMenu.setMode(SlidingMenu.RIGHT);
        slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
        slidingMenu.setShadowWidthRes(R.dimen.shadow_width);
        //menu.setShadowDrawable(R.drawable.shadow);
        slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_NONE);
        slidingMenu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
        slidingMenu.setShadowDrawable(R.drawable.shadowright);
        slidingMenu.setFadeDegree(0.35f);
        slidingMenu.attachToActivity((Activity) context, SlidingMenu.SLIDING_CONTENT);
        // 设置滑动菜单的视图界面
        slidingMenu.setMenu(R.layout.menu_tab4);
        initMenuView();
        slidingMenu.showContent();
    }

    public void initMenuView() {
        View menuView = slidingMenu.getMenu();
        fzrEdit = (EditText) menuView.findViewById(R.id.fzr);
        deviceedit = (EditText) menuView.findViewById(R.id.deviceedit);
        pddedit = (EditText) menuView.findViewById(R.id.pddedit);
        Button submitbtn = (Button) menuView.findViewById(R.id.submitbtn);
        submitbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                page = 1;
                postRequest();
                closeMenu();
                progressDialog.show();
            }
        });

        Button resetbtn = (Button) menuView.findViewById(R.id.resetbtn);
        resetbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                fzrEdit.setText("");
                deviceedit.setText("");
                pddedit.setText("");
                page = 1;
                postRequest();
                closeMenu();
                progressDialog.show();
            }
        });

    }

    public void showMenu() {
        if (slidingMenu.isMenuShowing()) {
            slidingMenu.showContent();
        } else {
            slidingMenu.showMenu();
        }
    }

    private void closeMenu() {
        if (slidingMenu.isMenuShowing()) {
            slidingMenu.showContent();
        }
    }

    public void menuAddClick() {

        if (pplist.size() == 1) {
            editposition = 0;
            getPPListRequest(true);
        } else {
            editItemContent(null);
        }
        //editItemContent(null);
    }

    public void showItemContent(DTBean bean) {
        builder = new AlertDialog.Builder(context);
        builder.setTitle("详情");
        LayoutDtBinding btBinding = DataBindingUtil.inflate(LayoutInflater.from(context), R.layout.layout_dt, null, false);
        btBinding.setData(bean);
        if (bean.getType() != null) {
            btBinding.type.setText("设备状态："+typevaluelist[Integer.valueOf(bean.getType())]);
        } else {
            btBinding.type.setText("设备状态：/");
        }

        btBinding.setType(BindingUtil.isDtType(context.getString(R.string.label_device_state), bean.getType()));
        builder.setView(btBinding.getRoot());
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                builder = null;
            }
        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //checkBinding.

                builder = null;
            }
        });
        builder.show();
    }

    public void editItemContent(DTBean bean) {
        builder = new AlertDialog.Builder(context);
        final LayoutEdtBinding edtBinding = DataBindingUtil.inflate(LayoutInflater.from(context), R.layout.layout_edt, null, false);
        edtBinding.spinnerpp.attachDataSource(spinnerdata);
        edtBinding.spinnetype.attachDataSource(Arrays.asList(typevaluelist));
        edtBinding.setData(bean);
        edtBinding.spinnerpp.addOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Log.e("Mytext", pplist.get(position).getCode() + "--" + pplist.get(position).getText());
                brand_id = pplist.get(position).getCode();
                brandname = pplist.get(position).getText();
            }
        });
        edtBinding.spinnetype.addOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                type = typekeylist[position];
            }
        });
        if (bean == null) {
            id = "";
            brandname = "";
            brand_id = "";
            type = "0";
            builder.setTitle("添加");
            edtBinding.spinnerpp.setSelectedIndex(0);
            edtBinding.spinnetype.setSelectedIndex(0);
        } else {
            id = bean.getId();
            type = bean.getType();
            brandname = bean.getBrandname();
            brand_id = bean.getBrand_id();
            builder.setTitle("修改");
            if (type == null) {
                edtBinding.spinnetype.setSelectedIndex(0);
            } else {
                edtBinding.spinnetype.setSelectedIndex(Integer.valueOf(type));
            }

            for (int i = 0; i < pplist.size(); i++) {
                if (pplist.get(i).getCode().equals(bean.getBrand_id())) {
                    edtBinding.spinnerpp.setSelectedIndex(i);
                    break;
                }
            }
        }


        builder.setView(edtBinding.getRoot());
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                builder = null;
            }
        });
        builder.setPositiveButton("确定", null);
        final AlertDialog dialog = builder.create();
        dialog.show();
        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Map<String, String> params = new HashMap<String, String>();
                params.put("call_number", BindingUtil.isEmpty(edtBinding.callnumber));
                if (brand_id.equals("")) {
                    Static.showToast(context, "请先选择品牌型号");
                    return;
                }
                if (BindingUtil.isEmpty(edtBinding.pdtesn).equals("")) {
                    Static.showToast(context, "请先填写PSD号");
                    return;
                }
                if (BindingUtil.isEmpty(edtBinding.deviceid).equals("")) {
                    Static.showToast(context, "请先填写电子串号");
                    return;
                }
                if (BindingUtil.isEmpty(edtBinding.fzr).equals("")) {
                    Static.showToast(context, "请先填写负责人");
                    return;
                }
                if (BindingUtil.isEmpty(edtBinding.fzrtelepone).equals("")) {
                    Static.showToast(context, "请先填写负责人号码");
                    return;
                }
                params.put("id", id);
                params.put("brand_id", brand_id);
                params.put("brandname", brandname);
                params.put("pdtesn", BindingUtil.isEmpty(edtBinding.pdtesn));
                params.put("device_id", BindingUtil.isEmpty(edtBinding.deviceid));
                params.put("type", type);
                params.put("fzr", BindingUtil.isEmpty(edtBinding.fzr));
                params.put("fzr_telepone", BindingUtil.isEmpty(edtBinding.fzrtelepone));
                params.put("remark", BindingUtil.isEmpty(edtBinding.remark));
                params.put("gdzcxh",BindingUtil.isEmpty(edtBinding.gdzcxh));
                params.put("policecode", PreferencesUtil.getInstance(context).getLastLoginPoliceCode());

                Gson gson = new Gson();
                String str = gson.toJson(params);
                Log.e("Mytext", "-->" + str);
                MNetHttp.getInstance().rxPostRequest(Static.INPUTTAB4, params, BaseBean.class, new InputResult());
                progressDialog.show();
                dialog.dismiss();

                //return;
            }
        });
    }

    public ActivityListBinding getBinding() {
        return binding;
    }

    public void postRequest() {
        /*initAdapter();
        statusListener.show();*/
        params.put("pdtesn", BindingUtil.isEmpty(pddedit));
        params.put("fzr", BindingUtil.isEmpty(fzrEdit));
        params.put("device_id", BindingUtil.isEmpty(deviceedit));
        params.put("page", page + "");
        params.put("rows", Static.rows);
        params.put("policecode", PreferencesUtil.getInstance(context).getLastLoginPoliceCode());

        Log.e("Mytext", "search-->" + GsonUtil.getJson(params));
        MNetHttp.getInstance().rxPostRequest(Static.RALIST, params, DTListBean.class, new ListRequestListener());
    }

    public void getPPListRequest(boolean isNull) {
        List<Map<String, Object>> datalist = new ArrayList<Map<String, Object>>();
        Map<String, Object> map1 = new HashMap<String, Object>();
        map1.put("url", Static.PPLIST);
        map1.put("param", new HashMap<String, String>());
        datalist.add(map1);
        MNetHttp.getInstance().rxListRequest(datalist, new AddResultListener(isNull));
    }

    public void reloadRequest() {
        page = 1;
        postRequest();
    }

    public void initAdapter() {
        if (adapter == null) {
            /*for(int i=0;i<20;i++){
                datalist.add(""+i);
            }*/

            adapter = new Tab4ItemAdapter(context, datalist, R.layout.item_tab4, null, new EditClick());
            adapter.setMode(Attributes.Mode.Single);
            binding.recycleview.setAdapter(adapter);
            binding.recycleview.addItemDecoration(new RVItemDecoration(30));
            binding.recycleview.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false));

        } else {
            adapter.notifyDataSetChanged();
        }
    }

    class InputResult implements HttpListener {

        @Override
        public void success(Object obj) {
            progressDialog.dismiss();
            if (((BaseBean) obj).getReturncode().equals("200")) {
                Static.showToast(context, "操作成功");
                Tab2RefreshEvent event = new Tab2RefreshEvent(true);
                EventBus.getDefault().post(event);
                //((Activity)context).finish();
                //finish();
            } else {
                Static.showToast(context, "操作失败");
            }
        }

        @Override
        public void fail(String msg) {
            progressDialog.dismiss();
            Static.showToast(context, msg);
        }
    }

    class ListRequestListener implements HttpListener {

        @Override
        public void success(Object obj) {

            if (((DTListBean) obj).getList() == null || ((DTListBean) obj).getList().size() == 0) {
                Static.showToast(context, context.getString(R.string.nodata));
                if (page == 1) {
                    statusListener.hide(false, "暂无更多数据");
                }
                binding.ptrLayout.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        binding.ptrLayout.refreshComplete();
                    }
                }, 20);
            } else {
                if (page == 1) {
                    datalist.clear();
                }
                if (((DTListBean) obj).getList().size() < Integer.valueOf(Static.rows)) {
                    Static.showToast(context, context.getString(R.string.nodata));
                }
                datalist.addAll(((DTListBean) obj).getList());
                initAdapter();
                statusListener.show();
                //Log.e("Mytext","size---->"+((JZListBean)obj).getList().get(1).getId());
                binding.ptrLayout.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        binding.ptrLayout.refreshComplete();
                    }
                }, 20);

            }
            progressDialog.dismiss();
        }

        @Override
        public void fail(String msg) {
            progressDialog.dismiss();
            statusListener.hide(false, msg);
        }
    }

    class AddResultListener implements RxHttpListener {
        private boolean isNull;

        public AddResultListener(boolean isNull) {
            this.isNull = isNull;
        }

        @Override
        public void finish() {

        }

        @Override
        public void fail(String msg) {

        }

        @Override
        public void next(Object obj) {
            if (pplist.size() == 1) {
                pplist.addAll(GsonUtil.getInstance().getArray(obj.toString(), BaseTypeBean[].class));
                for (BaseTypeBean bean : pplist) {
                    spinnerdata.add(bean.getText());
                }

                if (isNull) {
                    editItemContent(null);
                } else {
                    editItemContent((DTBean) datalist.get(editposition));
                }


            }

        }
    }

    class EditClick implements ItemEditClick {

        @Override
        public void delete(int position) {
            progressDialog.show();
            Static.showToast(context,"delete-->"+position);
            Map<String,String> delparams=new HashMap<String,String>();
            delparams.put("id",((DTBean)datalist.get(position)).getId());
            delparams.put("policecode", PreferencesUtil.getInstance(context).getLastLoginPoliceCode());
            MNetHttp.getInstance().rxPostRequest(Static.DELTAB4, delparams, BaseBean.class, new HttpListener() {
                @Override
                public void success(Object obj) {
                    if(((BaseBean)obj).getReturncode().equals("200")){
                        Static.showToast(context,"删除成功");
                        page=1;
                        postRequest();

                    }else{
                        Static.showToast(context,"删除失败");
                        progressDialog.dismiss();
                    }
                }

                @Override
                public void fail(String msg) {
                    Static.showToast(context,"删除失败,msg");
                    progressDialog.dismiss();
                }
            });
        }

        @Override
        public void edit(int position) {
            //Static.showToast(context, "edit-->" + position);
            if (pplist.size() == 1) {
                editposition = position;
                getPPListRequest(false);
            } else {
                editItemContent((DTBean) datalist.get(position));
            }

        }

        @Override
        public void click(int position) {
            //Static.showToast(context,"click-->"+position);
            showItemContent((DTBean) datalist.get(position));

        }
    }

    class Refresh implements RefreshListener {

        @Override
        public void refresh() {
            page = 1;
            postRequest();

        }

        @Override
        public void loadmore() {
            page++;
            postRequest();
        }
    }


}
